package com.bfsuol.common.controller;

import java.io.File;
import java.util.Iterator;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bfsuolcomponents.file.entity.FileManager;
import com.bfsuolcomponents.file.service.FileManagerService;
import com.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuolframework.core.utils.DateTimeUtils;
import com.bfsuolframework.core.utils.FileUtils;

/**
 * 录音以及上传controller
 * @author qiaowenbin
 */
@Controller
@RequestMapping("/record")
public class RecordController extends SpringControllerSupport{
	
	@Autowired
	private FileManagerService fileManagerService;
	
	@RequestMapping("/upload")
	public @ResponseBody String upload() throws Exception{
		Long id = null;
		
		Iterator<FileItem> iter = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(getRequest()).iterator();
		while (iter.hasNext()) {
		    FileItem item = iter.next();

		    if(!item.isFormField()){
		    	id = processUploadedFile(item);
		    }
		}
		
		return "{\"saved\": 1,\"id\": "+id+"}";
	}

	private Long processUploadedFile(FileItem item) throws Exception{
		// 上传
		String uploadPath = FileUtils.getUploadRealPath("files/records") + FileUtils.getDatePath()+"/";
		FileUtils.createFolder(uploadPath);
        String fileFullPath = getFileValidName(uploadPath, item.getName(), true, true); 
	    item.write(new File(fileFullPath));
	    
	    // 保存
		FileManager fileManager = new FileManager();
		fileManager.setFilePath(fileFullPath);
		fileManager.setUrl(FileUtils.realPath2Path(fileFullPath));
		fileManager.setFileRealname(FileUtils.getFileName(fileFullPath));
		fileManager.setFileTitle(item.getName());
		
		return fileManagerService.save(fileManager);	
	}

	private String getFileValidName(String filePath, String fileName,boolean format, boolean overwrite ){
		String fileValidName;
		if(format){
			String fileExt = FileUtils.getFileExt(fileName);
			fileValidName =  filePath + DateTimeUtils.getCurrentDateTimeString("yyyyMMddHHmmss") + (fileExt==null?"":"."+fileExt);
    	}else{
    		fileValidName =  filePath + fileName;
    	}
		if( !overwrite ){
			fileValidName = FileUtils.getValidFileName(fileValidName);
		}
		return fileValidName;
	}
	
}
